<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Category extends CI_Controller {
    private $data = array();

    public function  __construct() {
        parent::__construct();

        //check session
        if( !$this->session->userdata('isLoggedIn') ) {
            redirect(base_url().'admin', 'refresh');
        }

        //Load Helper and library
        $this->load->helper("url");
        $this->load->library("ci_smarty");
        $this->load->helper("text"); 
        $this->data['base_url'] = base_url();
        $this->data['root_url'] = $this->config->item('root_url');
        $this->load->library('pagination'); 

        //Load Model
        $this->load->Model("admin/Mcategory");

        $this->data['nameAdmin'] = $this->session->userdata('name');
        $this->data['main_selected_cate'] = 'category';
    }

    public function listCategory($curPage = 1 )
    {
        // config page
        $categoryPageConfig['base_url']      = base_url("list-category/");
        $categoryPageConfig['total_rows']    = $this->Mcategory->countCategory();
        $categoryPageConfig['per_page']      = 10;
        $categoryPageConfig['uri_segment']   = 2;
        $categoryPageConfig['cur_page']      = $curPage;

        $curOffset = $categoryPageConfig['per_page'] * ($curPage - 1);

        $this->pagination->initialize($categoryPageConfig);

        $this->data['pageList'] = $this->pagination->create_links();

        $this->data['listCategory'] = $this->Mcategory->getCategory($categoryPageConfig['per_page'],$curOffset);

        $this->data['sub_selected_cate'] = 'list-category';

        $this->ci_smarty->view('backend/list-category.tpl',$this->data); 
    }

    public function addCategory()
    {
        if($this->input->post()){
            $name = $this->input->post("name");
            $_POST['uname'] = mb_strtolower(url_title(removesign($name)));
            $data = $this->input->post();
            $this->Mcategory->insertCategory($data); 
            redirect(base_url()."admin/list-category.html"); 
        }

        $this->data['sub_selected_cate'] = 'add-category';
        $this->ci_smarty->view('backend/add-category.tpl',$this->data); 
    }

    public function updateCategory($category_uname)
    {
        $this->data['category'] = $this->Mcategory->getCategoryByUname($category_uname); 
        if($this->input->post()){
            $data = $this->input->post();
            $this->Mcategory->updateCategory($data); 
            redirect(base_url()."admin/list-category.html"); 
        }
       
        $this->ci_smarty->view('backend/update-category.tpl',$this->data); 
    }

    public function deleteCategory($category_id)
    {
        $this->Mcategory->deteleCategory($category_id); 
        redirect(base_url()."admin/list-category.html"); 
    }
}